<template>
  <div class="category-table-page">
    <el-card>
      <div class="header-bar">
        <span class="title">物料产品分类管理</span>
        <el-button type="primary" size="small" @click="onAddRoot">新增顶级分类</el-button>
      </div>
      <el-table
        :data="flatList"
        border
        default-expand-all
        :row-key="row => row.id"
        style="width: 100%;"
      >
        <el-table-column label="分类名称" min-width="240">
          <template #default="{ row }">
            <span :style="{ paddingLeft: (row.level * 22) + 'px' }">
              <el-icon v-if="row.hasChildren" style="margin-right:3px; color:#c1c7cd;">
                <arrow-down v-if="row.expanded" @click.stop="toggle(row)" />
                <arrow-right v-else @click.stop="toggle(row)" />
              </el-icon>
              <el-tag :type="row.enabled ? 'success' : 'info'" size="small" style="margin-right:8px;">
                {{ row.enabled ? '启用' : '停用' }}
              </el-tag>
              <span class="cat-name">{{ row.name }}</span>
              <span v-if="row.sort !== undefined" class="cat-sort">[排序:{{ row.sort }}]</span>
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="enabled" label="状态" width="150">
          <template #default="{ row }">
            <el-switch v-model="row.enabled" size="small"
              active-text="启用" inactive-text="停用" style="min-width:54px;" />
          </template>
        </el-table-column>
        <el-table-column prop="sort" label="排序号" width="70"/>
        <el-table-column label="操作" width="280" fixed="right">
          <template #default="{ row }">
            <el-button size="small" type="primary" link @click="onAddChild(row)">新增子类</el-button>
            <el-button size="small" type="info" link @click="onEdit(row)">编辑</el-button>
            <el-button size="small" type="danger" link @click="onDelete(row)">删除</el-button>
            <el-button size="small" type="warning" link @click="onMoveUp(row)">上移</el-button>
            <el-button size="small" type="warning" link @click="onMoveDown(row)">下移</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 编辑/新增弹窗 -->
    <el-dialog v-model="editDialog.visible" :title="editDialog.isEdit ? '编辑分类' : '新增分类'" width="400px">
      <el-form :model="editDialog.form" label-width="70px">
        <el-form-item label="分类名称">
          <el-input v-model="editDialog.form.name" />
        </el-form-item>
        <el-form-item label="排序">
          <el-input-number v-model="editDialog.form.sort" :min="1" />
        </el-form-item>
        <el-form-item label="启用状态">
          <el-switch v-model="editDialog.form.enabled" active-text="启用" inactive-text="停用" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="editDialog.visible = false">取消</el-button>
        <el-button type="primary" @click="onSaveEdit">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { ArrowRight, ArrowDown } from '@element-plus/icons-vue'

// ====== 原始树状数据 ======
const categoryTree = ref([
  {
    id: 1,
    name: '原料药',
    sort: 1,
    enabled: true,
    children: [
      { id: 11, name: '抗生素原料', sort: 1, enabled: true },
      { id: 12, name: '激素类原料', sort: 2, enabled: true }
    ]
  },
  {
    id: 2,
    name: '辅料',
    sort: 2,
    enabled: true,
    children: [
      { id: 21, name: '稳定剂', sort: 1, enabled: true },
      { id: 22, name: '增溶剂', sort: 2, enabled: false }
    ]
  },
  {
    id: 3,
    name: '包装材料',
    sort: 3,
    enabled: true,
    children: [
      { id: 31, name: '瓶类', sort: 1, enabled: true },
      { id: 32, name: '塞类', sort: 2, enabled: true },
      { id: 33, name: '袋/膜类', sort: 3, enabled: true }
    ]
  },
  {
    id: 4,
    name: '制剂成品',
    sort: 4,
    enabled: true
  }
])

// ====== 展开折叠处理 ======
const expandMap = ref({}) // id: bool



function toggle(row) {
  expandMap.value[row.id] = !row.expanded
}

// ====== 编辑/新增弹窗逻辑 ======
const editDialog = reactive({
  visible: false,
  isEdit: false,
  parent: null,
  form: { name: '', sort: 1, enabled: true, id: null }
})

function onAddRoot() {
  Object.assign(editDialog.form, { name: '', sort: calcMaxSort(categoryTree.value) + 1, enabled: true, id: null })
  editDialog.isEdit = false
  editDialog.parent = null
  editDialog.visible = true
}
function onAddChild(parent) {
  Object.assign(editDialog.form, { name: '', sort: calcMaxSort(parent.children) + 1, enabled: true, id: null })
  editDialog.isEdit = false
  editDialog.parent = parent
  editDialog.visible = true
}
function onEdit(row) {
  Object.assign(editDialog.form, { ...row })
  editDialog.isEdit = true
  editDialog.parent = row.parent
  editDialog.visible = true
}
function onSaveEdit() {
  if (!editDialog.form.name) {
    ElMessage.warning('分类名称不能为空')
    return
  }
  if (editDialog.isEdit) {
    const item = findNode(editDialog.form.id)
    Object.assign(item, editDialog.form)
  } else {
    const newId = getMaxId(categoryTree.value) + 1
    const node = { ...editDialog.form, id: newId }
    if (editDialog.parent) {
      if (!editDialog.parent.children) editDialog.parent.children = []
      editDialog.parent.children.push(node)
    } else {
      categoryTree.value.push(node)
    }
  }
  editDialog.visible = false
}

// ====== 删除节点 ======
function onDelete(row) {
  ElMessageBox.confirm(`确定要删除分类【${row.name}】?`, '提示', { type: 'warning' })
    .then(() => {
      removeNode(row.id)
      ElMessage.success('已删除')
    })
}

// ====== 上下移动（排序）======
function onMoveUp(row) {
  const siblings = getSiblings(row)
  const idx = siblings.findIndex(n => n.id === row.id)
  if (idx > 0) {
    [siblings[idx - 1], siblings[idx]] = [siblings[idx], siblings[idx - 1]]
    fixSort(siblings)
  }
}
function onMoveDown(row) {
  const siblings = getSiblings(row)
  const idx = siblings.findIndex(n => n.id === row.id)
  if (idx < siblings.length - 1) {
    [siblings[idx], siblings[idx + 1]] = [siblings[idx + 1], siblings[idx]]
    fixSort(siblings)
  }
}


// ====== 工具函数 ======
function findNode(id, arr = categoryTree.value) {
  for (const item of arr) {
    if (item.id === id) return item
    if (item.children) {
      const found = findNode(id, item.children)
      if (found) return found
    }
  }
  return null
}
function getSiblings(row) {
  // row.realRef 真实节点
  // row.parent 只是临时平铺结构的 parent
  // 所以得查 row.realRef 的父节点在原树里的 children
  // 这里可用 flatList 里 row.parent?.id 查到原始 parent，再拿其 children
  if (!row.parent) return categoryTree.value
  // 找到原树里的 parent 节点
  const parent = findNode(row.parent.id)
  return parent.children
}

function removeNode(id, arr = categoryTree.value) {
  const idx = arr.findIndex(item => item.id === id)
  if (idx !== -1) {
    arr.splice(idx, 1)
    return true
  }
  for (const item of arr) {
    if (item.children) {
      if (removeNode(id, item.children)) return true
    }
  }
  return false
}
function getMaxId(arr) {
  let max = 0
  for (const item of arr) {
    if (item.id > max) max = item.id
    if (item.children) {
      const subMax = getMaxId(item.children)
      if (subMax > max) max = subMax
    }
  }
  return max
}
function calcMaxSort(arr) {
  if (!arr || !arr.length) return 0
  return Math.max(...arr.map(i => i.sort || 0))
}
function fixSort(list) {
  list.forEach((item, i) => (item.sort = i + 1))
}

function makeFlat(tree, level = 0, parent = null) {
  const arr = []
  tree.forEach(node => {
    const expanded = expandMap.value[node.id] ?? true
    const hasChildren = !!(node.children && node.children.length)
    arr.push({
      ...node,
      parent,        // 只是用来渲染缩进
      realRef: node, // 这里加：指向原始节点
      level,
      expanded,
      hasChildren
    })
    if (hasChildren && expanded) {
      arr.push(...makeFlat(node.children, level + 1, node))
    }
  })
  return arr
}

const flatList = computed(() => makeFlat(categoryTree.value))

</script>

<style scoped>
.category-table-page {
  padding: 28px 38px 30px 38px;
  min-height: 100vh;
  background: #fff;
}
.header-bar {
  display: flex;
  align-items: center;
  margin-bottom: 18px;
}
.header-bar .title {
  font-size: 1.18rem;
  font-weight: 600;
  margin-right: 32px;
}
.cat-name {
  font-weight: 500;
}
.cat-sort {
  color: #bbb;
  font-size: 12px;
  margin-left: 6px;
}
</style>
